package com.feityz.handler.shef;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.model.variable.Variable;
import com.bstek.uflo.process.handler.DecisionHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
@ConditionalOnProperty(name = "system", havingValue = "yz")
public class XqzgDecisionHandler implements DecisionHandler {
    @Override
    public String handle(Context context, ProcessInstance processInstance) {
        List<Variable> agrees = context.getProcessService().createProcessVariableQuery().processInstanceId(processInstance.getId()).key("agree").list();

        List<Variable> zgqrs = context.getProcessService().createProcessVariableQuery().processInstanceId(processInstance.getId()).key("zgqr").list();

        List<Variable> type2s = context.getProcessService().createProcessVariableQuery().processInstanceId(processInstance.getId()).key("type2").list();

        Assert.isTrue(CollectionUtil.isNotEmpty(agrees), "请求变量agree为空");

        String agree = agrees.get(0).getValue().toString();

        String type2 = (CollectionUtil.isEmpty(type2s) ? "" : String.valueOf(type2s.get(0).getValue()));
        //(4和1表示从msr过来的)
        //"${agree=='1'?'提交':agree==2?'提交':agree==3?'确认':agree==11?'错误':'退回'}"
        if ("4".equals(type2) && ("1".equals(agree) || "-1".equals(agree))) {
            if ("-1".equals(agree)) {
                try {
                    context.getProcessService().deleteProcessVariable("zgqr", processInstance.getId());
                }catch (Exception ex){
                    ex.printStackTrace();
                }
                return "作废";
            }
            //当传4和1的时候要判断有没有被确认过
            Assert.isTrue(CollectionUtil.isNotEmpty(zgqrs), "请求变量zgqr为空");
        }

        if ("1".equals(agree) || "2".equals(agree)) {

            return "提交";
        }

        if ("3".equals(agree)) {
            return "确认";
        }

        if ("-2".equals(agree)) {
            return "退回";
        }

        if ("-1".equals(agree)) {
            return "退回";
        }

        return "";
    }

    @Override
    public String desc() {
        return "辖区整改判断";
    }
}
